<template>
  <div class="Main">
    <div class="MainTitle">音色列表</div>
    <div class="MianContent">
      <a-button
        type="primary"
        style="margin-bottom: 20px"
        size="large"
        @click="modalShow = true"
        >音色训练</a-button
      >
      <div class="TableView">
        <a-table
          :scroll="{ x: 2150, y: '' }"
          :columns="listfields"
          :data-source="listData"
          bordered
          size="middle"
          :pagination="false"
        >
          <div slot="indexNum" slot-scope="row, index">
            {{ (pageno * 1 - 1) * pagesize + (index.indexNum * 1 + 1) }}
          </div>
          <div slot="action" slot-scope="row, index">
            <!-- <a-button type="primary" size="small" @click="GoOrderDetail(index)">上架</a-button> -->
            <a-button
              style="margin: 0 10px 0 0"
              type="primary"
              size="small"
              @click="EditBrand(index)"
              >编辑</a-button
            >
            <a-popconfirm
              placement="bottom"
              ok-text="删除"
              cancel-text="取消"
              @confirm="DeleteItem(index)"
            >
              <template slot="title">
                <p>警告</p>
                <p>此操作将删除该数据源, 是否继续?</p>
              </template>
              <a-button type="danger" size="small">删除</a-button>
            </a-popconfirm>
            <!-- <a-button style="margin:0 0px 0 10px;" type="info" size="small" @click="BrandStatus(index)">{{index.status?'下架':'上架'}}</a-button> -->
          </div>
          <div slot="datasourceUrl" slot-scope="row, index">
            <div style="display: flex">
              <h3 style="flex-shrink: 0">m3u8Url：</h3>
              <div style="text-align: left">{{ row ? row : "无" }}</div>
            </div>
            <div style="display: flex">
              <h3 style="flex-shrink: 0">rtmpUrl：</h3>
              <div style="text-align: left">
                {{ index.rtmpUrl ? index.rtmpUrl : "无" }}
              </div>
            </div>
            <div style="display: flex">
              <h3 style="flex-shrink: 0">rtspUrl：</h3>
              <div style="text-align: left">
                {{ index.rtspUrl ? index.rtspUrl : "无" }}
              </div>
            </div>
          </div>
          <div slot="status" slot-scope="row, index">
            {{ row == 1 ? "在线" : "离线" }}
          </div>
        </a-table>
        <Pagination
          :total="total"
          v-model="pageno"
          :pageSize.sync="pagesize"
          @change="handlePageChange"
          @onShowSizeChange="onShowSizeChange"
        ></Pagination>
      </div>
      
      <a-modal
        title="训练音色"
        v-model="modalShow"
        centered
        ok-text="确认"
        :maskClosable="false"
        cancel-text="取消"
        @cancel="cancelBtn"
        @ok="modalSubmit"
        :width="700"
      >
        <div style="padding-left: 10px">
          <div class="flex">
            选择训练音色：
            <div>
              <a-select
                v-model="type"
                placeholder="选择音色"
                allowClear
                style="width: 220px"
                @change="selectType"
              >
                <a-select-option
                  :value="item.SpeakerID"
                  v-for="(item, index) in listData"
                  :key="index"
                >
                  {{ item.SpeakerID }}
                </a-select-option>
              </a-select>
              <div style="margin-top: 50px">
                <a-upload-dragger
                  v-model="fileList"
                  name="file"
                  :headers="headers"
                  :multiple="false"
                  :action="uploadUrl"
                  accept="audio/mp3,audio/wav"
                  :disabled="fileList.length >= 1"
                  @change="handleChange"
                  :beforeUpload="handleBeforeUpload"
                  @preview="handlePreview"
                  :showUploadList="false"
                >
                  <p class="ant-upload-drag-icon">
                    <a-icon type="inbox" />
                  </p>
                  <p class="ant-upload-text">上传文件</p>
                  <p class="ant-upload-hint" style="padding: 0 20px">
                    点击或拖拽文件上传，仅支持 mp3/wav 文件，仅可上传一个文件
                  </p>
                </a-upload-dragger>
                <div
                  style="padding: 20px 0 0; width: 100%"
                  class="flex align-center"
                  v-if="fileList.length"
                >
                  <audio
                    style="width: 100%"
                    :src="fileList[0].url"
                    controls="controls"
                  ></audio>
                  <a-icon
                    style="margin-left: 20px; font-size: 22px"
                    @click="delItem"
                    type="delete"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-modal>
      <!-- <a-modal v-model="LookImages" :footer="null" centered>
        <div style="margin: 10px">
          <img :src="SelectImg" style="width: 100%; height: 100%" />
        </div>
      </a-modal> -->
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from "vuex";
import { showErrors, showError, showSuccess } from "@/utils/showMsg";
import Pagination from "@/components/common/pagination.vue";
import UploadImage from "@/components/common/Upload";
import { DataSourceList } from "@/views/Columns/DataSource.js";
import axios from "axios";
import env from "@/config/env";
import Vue from "vue";
import { ACCESS_TOKEN, USER_DATA } from "@/store/mutation-types";
import { GetAiVoiceList } from "@/api/api.js";
export default {
  name: "list",
  components: {
    Pagination,
    UploadImage,
  },
  data() {
    return {
      modalShow: false,
      pageno: 1, //默认第几页
      pagesize: 10, //一页显示多少条数据
      total: 0, //总数
      listData: [], //表格数据
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      keyword: "",
      listfields: DataSourceList,

      type: undefined,
      fileList: [],
      uploadUrl: `${env.baseURL}manager/fileUploadAndDownload/upload`,
      listData: [],
      headers: {
        Accept: "application/json",
        Authorization: `${this.$ls.get(ACCESS_TOKEN)}`,
        "x-token": `${this.$ls.get(ACCESS_TOKEN)}`,
        "X-Requested-With": null,
        // 'user-id':`${this.$ls.get(USER_DATA).UserId}`,

        //   config.headers['access-token'] = `${token}`
        // config.headers['user-id'] = `${userid.UserId}`
        // config.headers['market-id'] = `${userid.MarketId}`
      },
    };
  },
  computed: {
    // ...mapState({
    //   listfields: (state) => state.ProductBrand.fields, //获取table头
    // }),
  },
  mounted() {
    // this.GetFields();
    this.GetList();
  },
  methods: {
    // ...mapActions({
    //   GetFields: "ProductBrand/GetFields", //获取table头
    // }),

    // 查看图片
    seeImg(row) {
      const that = this;
      that.LookImages = true;
      that.SelectImg = row.logo;
    },

    handleBeforeUpload(file) {
      console.log(file, "--");
    },

    handleChange(info) {
      console.log(info, "info");
      let fileList = [...info.fileList];
      fileList = fileList.map((file) => {
        // console.log(fileList);
        if (file.response) {
          if (file.response.code == 0) {
            file.url = file.response.data.file.url;
            file.id = file.response.data.file.ID;
          } else {
            file.status = "error";
          }
        }
        return file;
      });
      console.log("fileList", fileList);
      this.fileList = fileList;
      // this.changeFileList(this.fileList);
    },

    handlePreview(file) {
      console.log(file, "view");
    },

    // 删除
    delItem() {
      const that = this;
      that.fileList = [];
    },

    selectType() {
      console.log(this.type, "==");
    },

    // 获取数据列表API
    async GetList() {
      let that = this;
      let params = {
        keywords: that.keyword,
        page: that.pageno,
        pageSize: that.pagesize,
      };
      const res = await GetAiVoiceList(params);
      if (res.data.code == 0) {
        // console.log(res.data);
        const data = res.data.data;
        if (data.length > 0) {
          data.forEach((item, index) => {
            item.key = item.SpeakerID;
            item.indexNum = index;
            // item.CreatedAt = new Date(item.CreatedAt).toLocaleString(); //地区时间转换
            item.CreateTime = that
              .$moment(item.CreateTime)
              .format("YYYY-MM-DD  HH:mm:ss"); //时间戳转换成时间
            item.ExpireTime = that
              .$moment(item.ExpireTime)
              .format("YYYY-MM-DD  HH:mm:ss"); //时间戳转换成时间
          });
        }
        // console.log(data);
        // that.total = data.total;
        that.listData = data;
      } else {
        showError(res.data.msg);
      }
    },

    // 弹出确定
    async modalSubmit() {
      let that = this;
      if (!that.type) {
        showError("请选择训练音色");
        return;
      }
      if (!that.fileList.length) {
        showError("请上传训练音色文件");
        return;
      }
      const formData = new FormData();
      formData.append("file", that.fileList[0].originFileObj);
      formData.append("speakerId", that.type);
      console.log(formData, "===");

      const token = Vue.ls.get(ACCESS_TOKEN);
      axios({
        method: "post",
        url: `${env.baseURL}manager/ai/train`,
        data: formData,
        headers: {
          "x-token": token,
          Authorization: token,
          "Content-type": "multipart/form-data",
        },
      }).then((res) => {
        console.log(res);
        if (res.data.code == 0) {
          showSuccess("训练成功！");
          that.cancelBtn()
          that.GetList();
        } else {
          showError(res.data.msg);
        }
      });
    },
    // 弹出取消
    cancelBtn() {
      const that = this;
      that.fileList = [];
      that.type = undefined;
      // that.$refs.uploadImg.clearFile()
      that.modalShow = false;
    },

    //分页器
    handlePageChange(pageno, pagesize) {
      //点击第几页触发的函数
      this.pageno = pageno;
      this.pagesize = pagesize;
      this.GetList(); //这个是向后台请求的数据函数
    },
    //切换每页显示多少条
    onShowSizeChange(current, size) {
      //改变每页显示条目数的函数
      //pagesize 变化的回调
      this.pageno = current;
      this.pagesize = size;
      this.GetList(); //这个是向后台请求的数据函数
    },
  },
};
</script>

<style scoped lang="stylus">
.editable-row-operations a {
  margin-right: 12px;
}

.Main {
  border-radius: 10px;
  overflow: hidden;
  background: #fff;

  .MainTitle {
    font-size: 24px;
    color: #333;
    margin: 10px 20px;
    position: relative;
  }

  .MainTitle:before {
    content: '';
    width: 40px;
    height: 12px;
    background: linear-gradient(270deg, rgba(0, 158, 238, 0) 0%, rgba(0, 158, 238, 0.3) 100%);
    position: absolute;
    bottom: 2px;
    left: 0;
  }

  .MianContent {
    padding: 10px 20px 20px 20px;

    .MainTopAction {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .MainTopActionView {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .MainTopActionOne {
          margin-right: 30px;

          span {
            margin-right: 20px;
          }
        }

        .MainTopActionTwo {
          span {
            margin-right: 20px;
          }
        }
      }

      .MainTopActionThree {
        display: flex;
        align-items: center;
        margin-left: 20px;
      }
    }
  }
}
</style>